NVM.ScrollSnap = (function () {
  var __core = NOVEM.Core;

  return {
    init: function (selector) {
      selector = __core.getSelector(selector, false);
      if (selector.length < 2) {
        // 目前只做Banner和主内容2个区块的翻页，后期根据需求优化或回滚至scrollsnap效果
        return true;
      }

      if (!__core.getVars.elBody.classList.contains("is-expanded-menu")) {
        return true;
      }

      let scrollOffsetTop = __core.getOptions.scrollOffset;
      if (__core.getOptions.headerSticky) {
        scrollOffsetTop = document.querySelector("#header").offsetHeight;
      }
      // var elHeader = __core.getVars.elHeader;
      // __core.getVars.headerHeight = elHeader.offsetHeight;

      // var elHeaderInc = document.querySelector(".include-header");
      // if (elHeaderInc.classList.contains("include-topbar")) {
      //   __core.getVars.headerHeight =
      //     elHeader.offsetHeight + __core.offset(elHeader).top;
      // }

      var _throttle = function (fn, delay) {
        let timer = null;
        return (...args) => {
          if (!timer) {
            timer = setTimeout(() => {
              fn.apply(this, args);
              timer = null;
            }, delay);
          }
        };
      };

      selector[0].addEventListener(
        "wheel",
        _throttle((event) => {
          if (event.deltaY > 0) {
            window.scrollTo({
              top: selector[0].offsetHeight - scrollOffsetTop,
              left: 0,
              behavior: "smooth",
            });
            // document.querySelector('.down-png-box').click();
          }
        }, 50),
        { passive: true }
      );

      selector[1].addEventListener(
        "wheel",
        _throttle((event) => {
          if (
            event.deltaY < 0 &&
            selector[1].getBoundingClientRect().top >= scrollOffsetTop
          ) {
            window.scrollTo({
              top: 0,
              left: 0,
              behavior: "smooth",
            });
          }
        }, 50),
        { passive: true }
      );

      document.addEventListener(
        "keydown",
        _throttle((event) => {
          if (
            (event.keyCode == 40 || event.keyCode == 34) &&
            window.pageYOffset <= selector[0].offsetHeight - scrollOffsetTop
          ) {
            window.scrollTo({
              top: selector[0].offsetHeight - scrollOffsetTop,
              left: 0,
              behavior: "smooth",
            });
          }
          if (
            (event.keyCode == 38 || event.keyCode == 33) &&
            window.pageYOffset <= selector[0].offsetHeight - scrollOffsetTop
          ) {
            window.scrollTo({
              top: 0,
              left: 0,
              behavior: "smooth",
            });
          }
        }, 50)
      );

      __core.initFunction({
        class: "has-plugin-scrollsnap",
        event: "pluginScrollSnapReady",
      });
    },
  };
})();
